package com.lib.application;

import com.lib.dto.RentalAgentApplyDTO;
import com.lib.listener.event.RentalAgentApplyEvent;
import com.lib.model.RentalAgent;
import com.lib.model.WxAccount;
import com.lib.model.enums.RentalAgentStatusEnum;
import com.lib.repository.RentalAgentRepository;
import com.lib.repository.WxAccountReponsitory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by duqingxiang on 17/5/23.
 */
@Service
public class RentalAgentService {

    @Autowired
    RentalAgentRepository rentalAgentRepository;
    @Autowired
    WxAccountReponsitory wxAccountReponsitory;

    @Resource
    private ApplicationContext applicationContext;

    public void registerAgent(WxAccount account) {

        RentalAgent agent = RentalAgent.builder()
                .wxAccount(account)
                .createdDate(new Date())
                .build();
        rentalAgentRepository.save(agent);
    }

    public RentalAgent getRentalAgentByOpenId(String openId) {
        WxAccount wxAccount = wxAccountReponsitory.findWxAccountByOpenId(openId);
        if (wxAccount == null)
            return null;
        return wxAccount.getAgent();
    }

    public int submitAgentApply(RentalAgentApplyDTO applyDTO) {

        //TODO 验证验证码

        WxAccount wxAccount = wxAccountReponsitory.findWxAccountByOpenId(applyDTO.getOpenId());
        if (wxAccount == null) {
            return -10;
        }

        RentalAgent agent = wxAccount.getAgent();
        if (agent == null) {
            return -10;
        }

        agent.setName(applyDTO.getName());
        agent.setPhone(applyDTO.getPhone());
        agent.setStaffId(applyDTO.getStaffId());
        agent.setShopId(applyDTO.getShopId());
        agent.setStatus(RentalAgentStatusEnum.APPLY.getId());
        agent.setShopName(applyDTO.getShopName());

        rentalAgentRepository.saveAndFlush(agent);

        try {
            //给经纪人发送消息
            applicationContext.publishEvent(RentalAgentApplyEvent.builder().openId(applyDTO.getOpenId()).build());
        }catch (Exception e) {
            e.printStackTrace();
        }

        return 1;
    }
}
